package org.alexdalton.jira;

import java.util.ArrayList;

import org.alexdalton.jira.model.JiraServer;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class JiraServersDB extends SQLiteOpenHelper {
    SQLiteDatabase mDB;
    private static final int VERSION = 1;
    
    public JiraServersDB(Context context) {
        super(context, "servers", null, VERSION);
        mDB = getWritableDatabase();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS servers (_id integer PRIMARY KEY, name varchar(50), url varchar(256), user varchar(50), password varchar(50));");
    }

    /**
     * Called when the database needs to be upgraded.
     * 
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public void addServer(JiraServer server) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("name", server.getName());
        cv.put("url", server.getUrl());
        cv.put("user", server.getUser());
        cv.put("password", server.getPassword());

        db.insert("servers", "null", cv);
    }

    public ArrayList<JiraServer> getServerList() {
        ArrayList<JiraServer> servers = new ArrayList<JiraServer>();
        SQLiteDatabase db = getReadableDatabase();
        String[] cols = {"name", "url", "user", "password"};
        Cursor res = db.query("servers", cols, "1", null, null, null, null);
        for (int i = 0; i < res.getCount(); i++) {
            res.moveToPosition(i);
            servers.add(new JiraServer(res.getString(0), res.getString(1), res.getString(2), res.getString(3)));
        }
        res.close();
        return servers;
    }
}
